<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示文字 -->
      <el-alert title="添加商品信息" type="info" :closable="false" show-icon center :space="200"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="active*1" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 完成后展示的文章 -->
      <el-alert
        :title="'页面将在'+ seconds + '秒后跳转到商品列表页面'"
        type="success"
        center
        show-icon
        v-show="isShow"
      ></el-alert>
      <!-- 添加商品表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tabs栏 -->
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeLeave"
          @tab-click="tabClicked"
          v-show="!isShow"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodsCateList"
                :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id' }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals" size="mini">
                <el-checkbox :label="items" border v-for="(items,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传文件组件 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本框 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览图片对话框 -->
      <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
        <img :src="picPath" alt="图片" width="100%" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 步骤条起始步骤
      active: '0',
      //   添加商品表单对象
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加商品表单对象验证规则
      addFormRules: {
        goods_name: {
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        },
        goods_price: {
          required: true,
          message: '请输入商品价格',
          trigger: 'blur'
        },
        goods_weight: {
          required: true,
          message: '请输入商品重量',
          trigger: 'blur'
        },
        goods_number: {
          required: true,
          message: '请输入商品数量',
          trigger: 'blur'
        },
        goods_cat: {
          required: true,
          message: '请选择商品分类',
          trigger: 'blur'
        }
      },
      // 商品分类数据列表
      goodsCateList: [],
      //   参数列表
      manyTableData: [],
      //   属性列表
      onlyTableData: [],
      //   配置上传路径的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   控制对话框的显示与隐藏
      dialogVisible: false,
      //   要预览的图片路径
      picPath: '',
      //   剩余秒数
      seconds: 3,
      isShow: false
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    //   获取商品分类数据列表
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.goodsCateList = res.data
    },
    // 当级联选择器发生变化时触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 当tab栏标签页切换时触发，判断用户是否选择了商品分类
    beforeLeave(activeName, oldName) {
      if (oldName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
      return true
    },
    // 当切换tab标签页是，判断用户点击了哪一个标签页并且进行相应的操作
    async tabClicked(active) {
      if (active.index === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')
        }
        this.manyTableData = res.data
        this.manyTableData.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
      } else if (active.index === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取属性列表失败')
        }
        this.onlyTableData = res.data
      }
    },
    // 处理用户上传图片预览功能
    handlePreview(file) {
      this.dialogVisible = true
      // 图片路径
      this.picPath = file.response.data.url
    },
    // 图片上传成功后的回调函数
    handleSuccess(response) {
      const { tmp_path: pic } = response.data
      this.addForm.pics.push({ pic: pic })
    },
    // 图片移除以后的回调函数
    handleRemove(file) {
      // 获取图片路径
      const filePath = file.response.data.tmp_path
      // 根据图片路劲查找图片索引值
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 根据索引值删除数组中相应的图片
      this.addForm.pics.splice(index, 0)
    },
    // 提交表单
    add() {
      // 预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完必要的表单项再提交表单')
        }
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newItem = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newItem)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newItem = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newItem)
        })
        // lodash cloneDeep 因为级联选择器的v-model只能绑定数组，所以不能用jion方法直接操作addForm
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 发送请求
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.getGoodsCateList()
        this.$refs.addFormRef.resetFields()
        this.active = '6'
        setTimeout(() => {
            this.$router.push('/goods')
        }, 3000)
        var timer = setInterval(() => {
          if (this.seconds - 1 === 0) {
            clearInterval(timer)
          }
          this.seconds--
        }, 1000)
        this.$message.success('添加成功')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  watch: {
    active(active) {
      if (active === '6') {
        this.isShow = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.el-button {
  margin: 10px 0;
}
</style>
